package com.zzyl.nursing.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.framework.ai.AiInvoker;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.dto.HealthAssessmentDto;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.zzyl.nursing.vo.HealthReportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 健康评估Service业务层处理
 * 
 * @author hfy
 * @date 2025-05-20
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService
{
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;

    /**
     * 查询健康评估
     * 
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询健康评估列表
     * 
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment)
    {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }

    /**
     * 新增健康评估
     * 
     * @param dto 健康评估
     * @return 结果
     */
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private AiInvoker aiInvoker;
    @Override
    public Long insertHealthAssessment(HealthAssessmentDto dto)
    {     //1:从redis中读取pdf内容
        if (dto.getElderName()==null||"null".equals(dto.getElderName())){
            throw new RuntimeException("老人姓名为空");
        }
        if (dto.getIdCard()==null||"null".equals(dto.getIdCard())){
            throw new RuntimeException("老人身份证为空");
        }
        if (dto.getPhysicalExamInstitution()==null||"null".equals(dto.getPhysicalExamInstitution())){
            throw new RuntimeException("检测机构为空");
        }
        if (dto.getPhysicalReportUrl()==null||"null".equals(dto.getPhysicalReportUrl())){
            throw new RuntimeException("pdf为空");
        }
        String pdfTest = (String)redisTemplate.opsForHash().get(CacheConstants.UPLOAD_PDF_KEY, dto.getIdCard());

        //2:读取配置文件的prompt.txt,并替换里面的prompt
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("prompt.txt");
        String prompt = IoUtil.read(inputStream, StandardCharsets.UTF_8);
        prompt.replace("prompt", pdfTest);
        //2:调用千帆模型进行分析
        String jsonpdf = aiInvoker.invokeQianFanChat(prompt);

        //3:将数据转化为HealthAssessment对象
        HealthReportVo healthReportVo = JSON.parseObject(jsonpdf, HealthReportVo.class);

        //4:往HealthAssessment对象中依次存入内容
        String idCard = dto.getIdCard();
        HealthAssessment healthAssessment = new HealthAssessment();
        healthAssessment.setElderName(dto.getElderName());
        healthAssessment.setIdCard(idCard);
        healthAssessment.setPhysicalExamInstitution(dto.getPhysicalExamInstitution());
        healthAssessment.setPhysicalReportUrl(dto.getPhysicalReportUrl());
        healthAssessment.setBirthDate(IdcardUtil.getBirthDate(idCard).toLocalDateTime());
        healthAssessment.setAge(IdcardUtil.getAgeByIdCard(idCard));
        healthAssessment.setGender(IdcardUtil.getGenderByIdCard(idCard));
        double score = healthReportVo.getHealthAssessment().getHealthIndex();
        healthAssessment.setHealthScore(String.valueOf(score));
        healthAssessment.setTotalCheckDate(healthReportVo.getTotalCheckDate());
        healthAssessment.setRiskLevel(healthReportVo.getHealthAssessment().getRiskLevel());
        healthAssessment.setReportSummary(healthReportVo.getSummarize());
        healthAssessment.setDiseaseRisk(JSON.toJSONString(healthReportVo.getRiskDistribution()));
        healthAssessment.setAbnormalAnalysis(JSON.toJSONString(healthReportVo.getAbnormalData()));
        healthAssessment.setSystemScore(JSON.toJSONString(healthReportVo.getSystemScore()));
        healthAssessment.setSuggestionForAdmission(score>60?0:1);
        healthAssessment.setNursingLevelName(getNursingLevelName(score));
        healthAssessment.setAdmissionStatus(1);//未入住
        healthAssessment.setAssessmentTime(LocalDateTime.now());//评估时间
        //5:保存到数据库
        this.save(healthAssessment);

        //6:删除redis缓存;
        redisTemplate.opsForHash().delete(CacheConstants.UPLOAD_PDF_KEY, dto.getIdCard());
        return healthAssessment.getId();

    }

    /**
     * 推荐护理等级
     * @param healthScore
     * @return
     */
    private String getNursingLevelName(double healthScore) {
        if(healthScore<0 || healthScore>100){
            throw new BaseException("健康评分不在0-100之间");
        }

        String leveName = "正常";

        if(healthScore>=90) {
            leveName = "三级护理";
        } else if (healthScore>=80) {
            leveName = "二级护理";
        } else if (healthScore>=70) {
            leveName = "一级护理";
        } else if (healthScore>=60) {
            leveName = "特级护理";
        } else {
            leveName = "不建议入住";
        }

        return leveName;
    }

    /**
     * 修改健康评估
     * 
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment)
    {
        return updateById(healthAssessment) ? 1 : 0;
    }

    /**
     * 批量删除健康评估
     * 
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除健康评估信息
     * 
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }
}
